<?

class MAILER{
	function MAILER($type, $vars=null){
		global $DB, $_init, $Engine;
		$this->type = $type;
		$this->done	= array();
		if ($vars) {
			$this->_addvars($vars);
		}
		$this->update_db = false;
		if(!isset($this->title)) $this->title = $Engine->text->get( engine_get( 'mailer.title.default' )); //$DB->pair_lang('mailer.title.default');
		if(!isset($this->returnpath)) $this->returnpath = "noreply@" . engine_get('mail.ext'); 
	}
	
	function _addvars($vars){ foreach($vars as $k=>$v) if($k!=$this) $this->$k=$v; }
	
	function _parse_users($get,$from,$where){
		global $DB, $_init;
		
		$this->users = $DB->filter_key( "user_extend", $where, $get );
		//$this->users = $DB->parse($get,$from,$where,true);
	}
	
	function parseuser($id) {
		/*
			If $id is a number, get just that user. Otherwise, run $id as a 'where' clause.
		*/
		global $DB, $_init;
		$get_string = "ID, fname, lname, mail, lang, lletter";
		$from_string = "mod_user";
		if (is_numeric($id)) {
			$where_string = "id = " . $id;
		} else {
			$where_string = $id;
		}
		$this->users = $DB->filter_key( "user_extend", $where_string, $get_string ); //$DB->parse($get_string, $from_string, $where_string, true);
	}
	
	function _generate_newsletter($letterid, $lang, $userid=None) {
		/* WHAT'S THIS?
		   ============

			To get a working newsletter, the following elements need to be in place:
			In settings:
				* mod.letter.vars.[theme]. Points to a moddump by ID
			In moddump:
				* A JSON string composed of the following elements:
					- html_template. Points to a txtdump by ID. This is the template used for HTML emails.
					- plain_template. Points to a txtdump by ID. This is the template used for plain emails.
					- location. Points to a page by ID. This is the page used to display newsletters.
			In txtdump:
				* html_template and plain_template as mentioned above.
				* An entry with the title of the newsletter, as 'short'.
				* An entry with the body of the newsletter, as 'long'.
			In mod_letter:
				* letterid. Issue number
				* nameid. Points to a txtdump by ID.
				* contentid. Points to a txtdump by ID.
				* meta. A JSON string composed of:
					- year.
					- theme.
		*/
		global $DB, $_init, $Engine;

		$_letter = $DB->get('text.letter', "ID=". $letterid );
		$this->_addvars($_letter);
		$this->meta = json_decode($this->meta);
		$this->title = $Engine->text->get( $_letter["nameid"], "short", $lang ); //$DB->lang($_letter["nameid"], "short", $lang);
		$this->style = engine_get('url') . "/theme/" . $this->meta->theme . "/mailer";

		$this->_addvars( json_decode( $DB->query_direct( "select `json` from `moddump` where ID=". engine_get( "style:mod.letter.vars" )) ));  //$DB->parse_json(engine_get("style:mod.letter.vars")));
		$this->news_page = $DB->get( "page", 'ID='. $this->location );//$DB->parse('name', 'pages', 'id=' . $this->location);
		$this->url = engine_get('url') ."/" . $this->news_page['name'] . "?fresh=lang:".$lang."&letterid=".$letterid;

		if ($userid) {
			$this->parseuser($userid);
		}

		$replacevar = array(
			"%date%" => date("d.m Y",strtotime($this->pdate)),
			"%issue%" => $this->ID,
			"%year%" => $this->meta->year,
			"%url%" => $this->url,
			"%style%" => $this->style,
			"%title%" => utf8_decode( $Engine->text->get( $this->nameid, "short", $lang )), // $DB->lang($this->nameid, "short", $lang)),
			"%side%" => ($this->side)? $this->side:"",
			"%content%" => utf8_decode( $Engine->text->get( $this->textid, "long", $lang ))
		);

		$this->html = $this->template_gen($this->html_template, $replacevar); // Generate newsletter from HTML template
		$replacevar['%content%'] = strip_tags($replacevar['%content%']);
		$this->plain = $this->template_gen($this->plain_template, $replacevar); // Generate newsletter from plain template
	}
	
	function template_gen($template_id, $replacevar) {
		global $Engine;

		$template = $Engine->text->get( $template_id, "long" );
		foreach(array_keys($replacevar) as $key) {
			$template = str_replace($key, $replacevar[$key], $template);
		}
		$template = wordwrap($template); //Wordwrap to avoid exceeding maxlength of lines for sendmail.
		return $template;
	}
	
	function _send() {
		require_once ENGINE_CORE ."inc/Swift.php";
		require_once ENGINE_CORE ."inc/Swift/Connection/SMTP.php";
		require_once ENGINE_CORE ."inc/Swift/Plugin/Decorator.php";		
			
		try {
			$swift =& new Swift(new Swift_Connection_SMTP("localhost"));
			
			if($this->type=="plain") $message =& new Swift_Message($this->title,$this->plain);
			else {
				$message =& new Swift_Message($this->title);
				$message->attach(new Swift_Message_Part($this->plain));
				$message->attach(new Swift_Message_Part($this->html,"text/html"));
			}
			
			$message->headers->setLanguage(($this->lang)?$this->lang:LANG);
			$message->setReturnPath($this->returnpath);

			$recipients =& new Swift_RecipientList();
			#$recipients->addTo(new Swift_Address("bjorn+newslettertest@onedotonly.be", "Bjorn Kristinsson"));
			if($this->users) {
				$replacements = array();
				foreach($this->users as $ml) {
					if( $ml['fname'] || $ml['lname'] ){
						$recipients->addTo(new Swift_Address( $ml['mail'], $ml['fname']." ".$ml['lname']));
					} else {
						$recipients->addTo(new Swift_Address($ml['mail']));
					}
					$replacements[$ml['mail']] = array('{email}'=>$ml['mail'], '{id}'=>$ml['ID']);
					
					$this->done[] = $ml['ID'];
				}
			}
			
			$swift->attachPlugin(new Swift_Plugin_Decorator($replacements), "decorator");
			
			// if(count($this->users)) 
			$swift->batchSend($message, $recipients, $this->returnpath);
			

			
			// if($this->update_db) $q = mysql_query($this->update_db." ID IN(".implode(', ',$this->done ).")");
			return $this->done;
			
			
		} catch (Swift_ConnectionException $e) {
		  return "There was a problem communicating with SMTP: " . $e->getMessage();
		  
		} catch (Swift_Message_MimeException $e) {
		  return "There was an unexpected problem building the email:" . $e->getMessage();
		}
		
	}
}


?>